<?php
namespace Zaya\Lib\SSO;

use App\Http\Responses\ValidationResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Zaya\Lib\Exceptions\SimpleErrorException;

trait AuthenticatesClient
{
    /**
     * 进行 SSO Client 与 SSO Server 绑定
     *
     * @return \Illuminate\Http\Response
     */
    public function attach()
    {
        return (new Client())->attach();
    }

    public function showLoginForm()
    {
        // todo 判断配置，如果配置写了统一登录，则跳转到 SSO Server 登录页
        return view('sso.login');
    }

    /**
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|ValidationException|\Illuminate\View\View|object
     * @throws SimpleErrorException
     */
    public function login(Request $request)
    {
        // 登录验证
        $params = $request->all();
        $v = \Validator::make($params, [
            'username' => 'required|min:6|max:20',
            'password' => 'required|min:6|max:20',
        ]);
        if ($v->fails()) {
            return new ValidationException($v, new ValidationResponse());
        }
        try {
            return (new Client())->login($params['username'], $params['password']);
        } catch (NotAttachedException $e) {
            return (new Client())->attach();
        } catch (NotLoginException $e) {
            throw new SimpleErrorException('请求出错: 未登录');
        } catch (Exception $e) {
            throw new SimpleErrorException($e->getMessage(), max($e->getCode(), 400));
        }

        // 登录成功，跳转到前一页
        return response()->redirectTo(url()->previous());
    }

    /**
     * 获取用户信息
     *
     * @return array|object
     * @throws Exception
     * @throws NotAttachedException
     * @throws NotLoginException
     */
    public function userInfo()
    {
        return (new Client())->getUserInfo();
    }

    /**
     * 退出登录
     *
     * @return array|object
     * @throws Exception
     * @throws NotAttachedException
     * @throws NotLoginException
     */
    public function logout() {
        $client = new Client();
        $rs = $client->logout();
        $params = [
            'return_url' => url()->previous(),
        ];
        $url = $client->getRequestUrl('login', $params);
        if (request()->ajax()) {
            return \response()->json([
                'code' => 'NotLogin',
                'handle' => 'redirect',
                'url' => $url,
                'message' => $rs[0],
            ], NotLoginException::$status);
        }
        if (request('callback')) {
            return \response()->jsonp(request('callback'), [
                'code' => 'NotLogin',
                'handle' => 'redirect',
                'url' => $url,
                'message' => $rs[0],
            ]);
        }
        return response()->redirectTo($url);
    }
}